<?php
/**
 * Created by PhpStorm.
 * User: chency
 * Date: 2018/11/9
 * Time: 19:42
 */

namespace app\login\controller;

use think\Db;
use think\Exception;
use think\Jwt;
use think\Request;
use think\Session;
use traits\controller\Jump;

class Index extends Base {
    use Jump;

    public function index(Request $request) {
        $cellphone = $request->post('cellphone');
        $password  = $request->post('password');
        $jwt       = Jwt::getInstance();
        //判断是否已经登录
        if (!empty($this->uid)) {
            $userInfo = $jwt->get('user_info');
            $userInfo = json_decode($userInfo, true);
            $this->redirect("/{$userInfo['user_type']}.html");
        }
        if (empty($cellphone) || empty($password) || is_array($password)) {
            $failTime = time() + 3600;
            $jwt->set('login_time', $failTime);
            //给用户登录的权限
            return view('index', [

            ]);
        } else {
            try {
                $failTime = $jwt->get('login_time');
                if (time() - $failTime > 60) throw new Exception('页面过期，请刷新后再试' . $failTime);
                $password = md5($password);
                $userInfo = Db::table('tps_user')->field('id,password,nick,user_type')->where(['cellphone' => $cellphone, 'password' => $password])->find();
                if ($password != $userInfo['password']) {
                    throw new Exception('密码错误');
                } else {
                    Session::set('uid', $userInfo['id']);
                    $jwt->set('uid', $userInfo['id']);
                }
                //保存UserInfo
                unset($userInfo['id']);
                unset($userInfo['password']);
                $jwt->set('user_info', json_encode($userInfo));
            } catch (Exception $e) {
                return json(['message' => $e->getMessage()], 401);
            }
            return json(['message' => 'SUCCESS'], 200);
        }
    }
}